<template>
  <div>
    <input type="file" accept=".docx" @change="handleFileUpload" />
    <button @click="insertMarkDown">模拟markdown数据</button>
    <button @click="editor.chain().focus().toggleBold().run()">加粗</button>
    <editor-content :editor="editor" />
    <pre v-if="markdown">{{ markdown }}</pre>
    <div v-if="error" class="error">{{ error }}</div>
  </div>
</template>
 
<script>
import { Editor, EditorContent } from "@tiptap/vue-2";
import StarterKit from "@tiptap/starter-kit";
import { markdownData } from "./js/markdown.js";

import mammoth from "mammoth";
import TurndownService from "turndown";
// import { parseStyles, convertDocxToHtml } from "../utils/docxParser";

export default {
  components: {
    EditorContent,
  },

  props: {
    value: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      editor: null,
      markdown: "",
      error: "",
    };
  },

  watch: {
    value(value) {
      // HTML
      const isSame = this.editor.getHTML() === value;

      // JSON
      // const isSame = JSON.stringify(this.editor.getJSON()) === JSON.stringify(value)

      if (isSame) {
        console.log("this.editor.getHTML()====", isSame);
        return;
      }

      this.editor.commands.setContent(value, false);
    },
  },

  mounted() {
    this.editor = new Editor({
      content: this.value,
      extensions: [StarterKit],
      onUpdate: () => {
        // HTML
        this.$emit("input", this.editor.getHTML());

        // JSON
        // this.$emit('input', this.editor.getJSON())
      },
    });
  },
  methods: {
    handleFileUpload() {
      this.error = "";
      const file = event.target.files[0];

      // 校验文件类型
      if (!file || !file.name.endsWith(".docx")) {
        this.error = "仅支持 .docx 文件";
        return;
      }

      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          // Step 1: 将 DOCX 转为 HTML
          const { value: html } = await mammoth.convertToHtml({
            arrayBuffer: e.target.result,
          });

          // Step 2: 将 HTML 转为 Markdown
          const turndown = new TurndownService({
            headingStyle: "atx",
            codeBlockStyle: "fenced",
            emDelimiter: "*",
          });

          this.markdown = turndown.turndown(html);
        } catch (err) {
          this.error = "转换失败: " + err.message;
        }
      };
      reader.readAsArrayBuffer(file);
    },
    // 导入Markdown数据
    insertMarkDown() {
      this.editor.commands.setContent(markdownData);
    },
  },

  beforeDestroy() {
    this.editor.destroy();
  },
};
</script>
<style lang="scss">
.mainContent {
  display: flex;
  .toc-sidebar {
    width: 20%;
    .toc-item {
      white-space: nowrap;
      text-align: left;
      text-overflow: ellipsis;
      overflow: hidden;
      cursor: pointer;
      margin: 4px 0;
    }
  }
  .editorElement {
    flex: 1;
  }
}
/* 全局文档样式 */
.doc-paragraph {
  margin: 12px 0;
  line-height: 1.6;
  font-family: "SimSun", serif;
}

/* 表格样式 */
table {
  border-collapse: collapse;
  margin: 1rem 0;
  table-layout: fixed;
  max-width: 100% !important;
}

td,
th {
  padding: 8px;
  min-width: 50px;
  position: relative;
  vertical-align: top;
}

th {
  font-weight: bold;
}

/* 合并单元格提示 */
[colspan]:not([colspan="1"]),
[rowspan]:not([rowspan="1"]) {
  background-color: #f0f8ff;
}

/* 列宽调整手柄 */
.column-resize-handle {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: #adf;
  pointer-events: none;
  cursor: pointer;
}

img {
  max-width: 100%;
  height: auto;
  border: 1px solid red !important; /* 调试用边框 */
}
/* 全局样式或组件内样式 */
.editor-image {
  border: 1px solid #ddd !important; /* 调试用边框 */
}

/* 覆盖潜在冲突样式 */
.ProseMirror {
  width: 100%;
  img {
    max-wdith: 100% !important;
  }
  .tableWrapper {
    display: flex;
    align-items: center;
  }
  table {
    border-collapse: collapse;
    border: 1px solid #000;
    margin: 5px;
  }
  td,
  td {
    border: 1px solid #000; /* 边框颜色和粗细 */
    padding: 8px; /* 内边距 */
  }
}
/* ✅ 确保图片可见性 */
.resizable-image {
  display: block !important;
  max-width: 100%;
  height: auto;
  margin: 10px auto;
  position: relative !important;
}

.resizable-image::after {
  content: "";
  position: absolute;
  bottom: -8px;
  right: -8px;
  width: 16px;
  height: 16px;
  background: #2196f3;
  border-radius: 50%;
  cursor: nwse-resize;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
button {
  margin: 5px;
}

/* 统一对齐样式 */
.ProseMirror {
  p[data-text-align],
  h1[data-text-align],
  h2[data-text-align] {
    &[data-text-align="left"] {
      text-align: left;
    }
    &[data-text-align="center"] {
      text-align: center;
    }
    &[data-text-align="right"] {
      text-align: right;
    }
  }

  /* 图片浮动处理 */
  .float-image {
    max-width: 60%;
    &[data-align="left"] {
      float: left;
      margin: 0 1rem 1rem 0;
    }
    &[data-align="right"] {
      float: right;
      margin: 0 0 1rem 1rem;
    }
    &[data-align="center"] {
      display: block;
      margin: 1rem auto;
    }
  }
}

/* 清除浮动 */
.ProseMirror::after {
  content: "";
  display: table;
  clear: both;
}
</style>
